from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SPUSpecification, SPU
from meiduo_admin.serializers.specs import SPUSpecificationSerializer, SPUserializer
from meiduo_admin.utils import PageNum, SpecsPermission


class SpecsView(ModelViewSet):
    serializer_class = SPUSpecificationSerializer
    queryset = SPUSpecification.objects.all()
    pagination_class = PageNum
    permission_classes = [IsAdminUser]
    permission_classes_by_action = {'create': [SpecsPermission],
                                    'update': [SpecsPermission],
                                    'destroy': [SpecsPermission]
                                    }

    def simple(self,request):
        # 获取商品spu的id和name
        spus = SPU.objects.all()
        serializer = SPUserializer(spus,many=True)


        return Response(serializer.data)

    def get_permissions(self):
        try:
            # return permission_classes depending on `action`
            return [permission() for permission in self.permission_classes_by_action[self.action]]
        except KeyError:
            # action is not set return default permission_classes
            return [permission() for permission in self.permission_classes]

